/**
 * 
 */
package com.res.simulator.handler;

import java.io.IOException;
import java.util.Map;

import org.apache.log4j.Logger;

import com.res.common.handler.CommonHandler;
import com.res.simulator.model.CatalogManagementControlModel;
import com.res.simulator.model.WADLScanModel;
import com.res.simulator.plugins.MessageCommunicationClientPlugin;
import com.res.simulator.transformer.WADLScanTransformer;
import com.res.simulator.view.WADLDataView;
import com.res.system.utils.SimulatorUtilities;
import com.res.system.utils.SimulatorUtilities.ConfigData;
import com.sip.comserver.communication.CommunicationMessage;

/**
 * @author Dhanushka Ariyasingha.
 * 
 */
public class ScanPageHandler implements CommonHandler<WADLDataView, WADLScanModel> {

	private static final Logger logger = Logger.getLogger(CatalogManagementHandler.class);

	public WADLDataView process(final WADLScanModel model) throws Exception {

		// TODO Auto-generated method stub
		final WADLScanTransformer transformer = new WADLScanTransformer();
		final Map<String, Object> domainCollection = transformer.transformModelToDomian(model);

		final Map<String, Object> returnCollection = commit(domainCollection);

		WADLDataView view = null;
		
		if(null != returnCollection)
		    view = transformer.transformDomianToView(returnCollection);

		return view;
	}

	/**
	 * Commited data to back end and return message will be directed to
	 * 
	 * @param domainCollection
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	private Map<String, Object> commit(final Map<String, Object> domainCollection) throws IOException, ClassNotFoundException {

		final CommunicationMessage message = new CommunicationMessage();

		final String serverAddress = SimulatorUtilities.getConfigData(ConfigData.SERVER_ADDRESS);
		final String port = SimulatorUtilities.getConfigData(ConfigData.SERVER_PORT);

		logger.info("Message Header==>" + "JOBType:cm" + "|ID:" + serverAddress + "|Port:" + port + "|Executor:ScanWADL");

		message.setMessageHeader("JOBType:GenericAPIExecution|Executor:ScanWADL|ID:" + serverAddress + "|Port:" + port);
		message.setObject(domainCollection);

		final MessageCommunicationClientPlugin plugin = new MessageCommunicationClientPlugin();
		final CommunicationMessage returnedMessage = plugin.invoke(message);
		
		Map<String, Object> returnCollection = null;
		final Object returnObj = returnedMessage.getObject();
		
		if(null != returnObj)
		    returnCollection = (Map<String, Object>) returnObj;


		return returnCollection;
	}

}